#encoding:utf8
import time
import random
import string
import hashlib
import requests

class Sign:
    def __init__(self, jsapi_ticket, url):
        self.ret = {
            'nonceStr': self.__create_nonce_str(),
            'jsapi_ticket': jsapi_ticket,
            'timestamp': self.__create_timestamp(),
            'url': url
        }

    def __create_nonce_str(self):
        x=''.join(random.choice(string.ascii_letters + string.digits) for _ in range(15))
	print "nonce:",x
	return x

    def __create_timestamp(self):
        y=int(time.time())
	print "time:",y
	return y

    def sign(self):
        string = '&'.join(['%s=%s' % (key.lower(), self.ret[key]) for key in sorted(self.ret)])
        print string
        self.ret['signature'] = hashlib.sha1(string).hexdigest()
        return self.ret

if __name__ == '__main__':
    # 获取ACCESS_TOKEN的地址：
	#curl  'https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=wx9cdf4b0ea43a8352&secret=b24c31b26c407ecf8572e66ab147b7b5'
    # 获取jspai——ticket的地址：
	#curl  'https://api.weixin.qq.com/cgi-bin/ticket/getticket?access_token=53_XgeWBQLg14plS0rx9yrQltZ_HUeR3nGzAP0dx52on-1R53Ti3vmo0HCkyw_Vnsav3mASF6nb44W7LnK3tpcGaMCmNBZsnFFjQeQB1XVLMfTWIZnYZSkwywBHCloy0Uh6TC8A6J7WZ03JQXltCAKaADAJHR&type=jsapi'
	#之前总是invalid signature，就是因为上面的type=wx_card，正确的应该是type=jsapi
    sign = Sign('O3SMpm8bG7kJnF36aXbe85i_e6MMj6pVpqxUMoVDdBT1aVlMyEsudJNOPZv7ZqlrqtMQYRdEczdHcX1f0ls-ww', 'http://www.cynfsy.com/cheungssh/static/html/test2.html')
    print sign.sign()
